package com.ccteam.shared.domain.user

import com.ccteam.model.Resource
import com.ccteam.model.user.UserNoPasswordDTO
import com.ccteam.network.ApiError
import com.ccteam.network.ApiResult
import com.ccteam.shared.core.UserCore
import com.ccteam.shared.data.user.UserRepository
import com.ccteam.shared.domain.SuspendUseCase
import com.ccteam.shared.domain.user.EditSelfInformationDataUseCase.EditSelfInformationRequest
import kotlinx.coroutines.Dispatchers
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/3/20
 *
 * 修改个人信息Domain层
 * 传入[EditSelfInformationRequest] 个人信息数据
 * 返回[Nothing]
 */
class EditSelfInformationDataUseCase @Inject constructor(
    private val userCore: UserCore,
    private val userRepository: UserRepository
): SuspendUseCase<EditSelfInformationDataUseCase.EditSelfInformationRequest, Nothing?>(
    Dispatchers.IO
) {
    override suspend fun execute(parameters: EditSelfInformationRequest): Resource<Nothing?> {
        val token = userCore.userInfo.value.userToken
        if(!userCore.isLogin.value || token.isNullOrEmpty()){
            return Resource.Error(ApiError.unknownCode,"登录状态异常")
        }

        return when (val result = userRepository.editUserInfo(token,
            UserNoPasswordDTO(parameters.id,parameters.userName,parameters.userBirthday,
                parameters.userIntroduction,parameters.userGender,
                parameters.userImgUrl)
        )) {
            is ApiResult.Success -> {
                Resource.Success(null)
            }
            is ApiResult.Failure -> {
                Resource.Error(result.errorCode,result.errorMsg)
            }
            else -> {
                Resource.Error(ApiError.serverErrorCode,"未知错误")
            }
        }
    }

    data class EditSelfInformationRequest(
        val id: String,
        var userName: String? = null,
        var userIntroduction: String? = null,
        var userBirthday: String? = null,
        var userGender: String? = null,
        var userImgUrl: String? = null
    )
}